package com.xxx.modules.sys.service.impl;

import com.xxx.common.utils.R;
import com.xxx.modules.sys.domain.SysUserTokenDomain;
import com.xxx.modules.sys.oauth2.TokenGenerator;
import com.xxx.modules.sys.service.SysUserLoginService;
import com.xxx.modules.sys.service.SysUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by ChenXuefei on 2017/10/13.
 */
@Service("SysUserLoginService")
public class SysUserLoginServiceImpl implements SysUserLoginService {
    /** token的过期时间*/
    private final static int EXPIRE = 12 * 3600;

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Override
    public void updateUserToken(Long userId) {
        String token = TokenGenerator.generateValue();
        SysUserTokenDomain userTokenDomain = new SysUserTokenDomain();
        userTokenDomain.setToken(token);
        userTokenDomain.setUserId(userId);
    }

    @Override
    public R saveToken(Long userId) {
        SysUserTokenDomain userTokenDomain = sysUserTokenService.queryById(userId);
        Date now = new Date();
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
        String token = TokenGenerator.generateValue();
        if(userTokenDomain==null){
            //如果该用户没有token
            userTokenDomain = new SysUserTokenDomain();
            userTokenDomain.setToken(token);
            userTokenDomain.setUserId(userId);
            userTokenDomain.setExpireTime(expireTime);
            userTokenDomain.setUpdateTime(now);
            sysUserTokenService.add(userTokenDomain);
        }else{
            //如果该用户已存在token,则对原有的值进行更改
            userTokenDomain.setToken(token);
            userTokenDomain.setExpireTime(expireTime);
            userTokenDomain.setUpdateTime(now);
            sysUserTokenService.updateBySelective(userTokenDomain);
        }
        R r = R.ok().put("token",token).put("expire",expireTime);
        return r;
    }
}
